#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define LOCK_FILE_NAME ".lock"
#define MAX_RETRIES 3
#define RETRY_DELAY 1

static int lock_fd = -1;

static void cleanup_handler(int signo) {
    (void)signo;
    if (lock_fd != -1) {
        close(lock_fd);
        unlink(LOCK_FILE_NAME);
    }
    exit(1);
}

static int acquire_lock() {
    struct sigaction sa;
    sa.sa_handler = cleanup_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Failed to set up signal handler");
        return -1;
    }
    if (sigaction(SIGTERM, &sa, NULL) == -1) {
        perror("Failed to set up signal handler");
        return -1;
    }

    int retries = 0;
    while (retries < MAX_RETRIES) {
        lock_fd = open(LOCK_FILE_NAME, O_RDWR | O_CREAT | O_EXCL, 0600);
        if (lock_fd != -1) {
            return 0;
        }
        
        if (errno != EEXIST) {
            perror("Failed to create lock file");
            return -1;
        }
        
        retries++;
        if (retries < MAX_RETRIES) {
            sleep(RETRY_DELAY);
        }
    }
    
    return -1;
}

int main(int argc, char *argv[]) {
    int wait_time_sec;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <wait_time_sec>\n", argv[0]);
        return 1;
    }
    
    wait_time_sec = atoi(argv[1]);

    if (acquire_lock() == -1) {
        fprintf(stderr, "Failed to acquire lock after %d retries\n", MAX_RETRIES);
        return 1;
    }

    printf("Lock acquired\n");
    if (wait_time_sec > 0) {
        printf("Waiting for %d seconds\n", wait_time_sec);
        sleep(wait_time_sec);
    }

    if (close(lock_fd) == -1) {
        perror("Failed to close lock file");
        return 1;
    }
    
    if (unlink(LOCK_FILE_NAME) == -1) {
        perror("Failed to remove lock file");
        return 1;
    }
    
    printf("Lock released\n");
    return 0;
}
